package idv.arthur.work;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FileDownload
 */
//@WebServlet(description = "抓取指定SN的檔案，變更回原本的名稱後回傳下載", urlPatterns = { "/FileDownload" })
public class FileDownload extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileDownload() {
        super();
    }

    private static final int BYTES_DOWNLOAD = 1024;
    
     

    
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		int fileSN = Integer.parseInt(request.getParameter("sn"));
		
		Widgets wid = new Widgets();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String strSQL = "SELECT ori_filename FROM tms_mrfileupload WHERE sn=?";
		String returnResult = "";
		String loginUser = request.getParameter("loginUser");	//要記錄下載的人是誰
		String ori_fileName = ""; //記錄上傳時的原始檔案名稱
		InputStream is = null;
		OutputStream os = null;
		
		ServletContext context  = getServletConfig().getServletContext();
	    String mimetype = context.getMimeType(String.valueOf(fileSN));
		
		
		try {
			conn = wid.getConn(true);
			ps = conn.prepareStatement(strSQL);
			ps.setInt(1, fileSN);
			rs = ps.executeQuery();
			
			if (rs.next()) {
				ori_fileName = rs.getString("ori_filename");
				System.out.println("原始檔名是："+ori_fileName);
				response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
				response.setHeader("Content-Disposition","attachment;filename="+ori_fileName);
				File uploadedFile = new File(saveDirectory + fileSN);
				is = new FileInputStream(uploadedFile);
				int read=0;
				byte[] bytes = new byte[BYTES_DOWNLOAD];
				os = response.getOutputStream();
				while((read = is.read(bytes))!= -1){
					os.write(bytes, 0, read);
				}
				os.flush();
				os.close();				
			} else {
				returnResult ="所要下載的檔案已遺失，請洽詢網站管理人員！";
			}
		} catch (SQLException e) {
			returnResult = wid.keepErrorMes(conn, ps, e, "", true);
		}  catch (Exception e) {
			returnResult = wid.keepErrorMes(conn, ps, e, "", true);
		} finally {
			try {
				if (rs!= null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				returnResult = e.toString();
			}
		}
	}
	
	//final String saveDirectory = "C:\\";
	final String saveDirectory = "/disk3/fileupload/";
}